﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TPA.DataAccess;
using System.Reflection;
using System.Linq.Expressions;


namespace TVProgramAnalyst.TimeLine
{

    public partial class frmProgramResult : Form
    {

        

        Program _program;
        SaveMode _savemode;
        List<Program> _list = new List<Program>();
        List<Filter> _filterlist = new List<Filter>();
        List<ProgramDisplayer> _programdisplaylist;

        int _selectedindex,_firstrowindex;
        public frmProgramResult()
        {
            InitializeComponent();
        }

        private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void Save_To_Database_Load(object sender, EventArgs e)
        {
                      //dgvProgramList.AutoGenerateColumns = false;

            LoadProgramList();
            dgvProgramList.Columns[0].Visible = false;
            splitContainer2.Panel1Collapsed = true;
            splitContainer3.Panel1Collapsed = true;
            //if (_list.Count > 0)
            //{
            //    _program = _list[0];
            //    BindProgram(_program);
            //}

            //BindFilter();
            
        }

        private void BindFilter()
        {
            //cProperty.DataSource = typeof(ProgramDisplayer).GetProperties().Select(p => p.GetCustomAttributesData().Count>0?p.GetCustomAttributesData()[0].ConstructorArguments[0].Value:p.Name).ToList();
            //dgvFilters.DataSource = _filterlist;
            //dataGridView1.DataSource = _filterlist.AsEnumerable();
            lstFilters.Items.Clear();
            foreach (Filter f in _filterlist)
            {
                lstFilters.Items.Add(f.ToString());
            }
        }

        private void LoadProgramList()
        {
            if (this.Owner==null||this.Owner.GetType() == typeof(TVProgramAnalyst.Main))
            {
                PrepareList();
                //toolbar1.Visible = false;
                btnShowProgramOption.Enabled = false;
                this.WindowState = FormWindowState.Maximized;
            }
            else
            {
                PrepareList(menuNewProgram.Checked, menuExistingProgram.Checked, menuConflictProgram.Checked);
                btnShowProgramOption.Enabled = true;
            }
        }



        private void PrepareList()
        {
            _list = BLLFactory.ProgramBLL.GetPrograms().ToList();
            var datasource = (from p in _list
                             select new ProgramDisplayer()
                             {
                                 Id = p.Id,
                                 Name = p.Name,
                                 EnglishName = p.EnglishName,
                                 Catetory = p.Subcategory!=null?p.Subcategory.Name:"",
                                 EnglishCategory = p.Subcategory!=null?p.Subcategory.EnglishName:"",
                                 Area = p.ProducingArea!=null?p.ProducingArea.Name:"",
                                 Source = p.ProgramSource!=null?p.ProgramSource.Name:"",
                                 Date = p.ProducingDate,
                                 ProducingType =p.ProducingType!=null? p.ProducingType.Name:""
                             }).ToList();
            _programdisplaylist = datasource;
            dgvProgramList.DataSource = datasource;
            //return _list;
        }

        private void PrepareList(bool newprograms, bool exisingprograms, bool conflictprograms)
        {
            _list = new List<Program>();
            if (newprograms)
                _list.AddRange(TPAProgram._NewPrograms);
            if (conflictprograms)
                _list.AddRange(TPAProgram._ConflictPrograms);
            if (exisingprograms)
                _list.AddRange(TPAProgram._ExistingPrograms);
            var datasource = (from p in _list
                              select new ProgramDisplayer()
                              {
                                  Id = p.Id,
                                  Name = p.Name,
                                  EnglishName = p.EnglishName,
                                  Catetory = p.Subcategory != null ? p.Subcategory.Name : "",
                                  EnglishCategory = p.Subcategory != null ? p.Subcategory.EnglishName : "",
                                  Area = p.ProducingArea != null ? p.ProducingArea.Name : "",
                                  Source = p.ProgramSource != null ? p.ProgramSource.Name : "",
                                  Date = p.ProducingDate,
                                  ProducingType = p.ProducingType != null ? p.ProducingType.Name : ""
                              }).ToList();
            _programdisplaylist = datasource;
            dgvProgramList.DataSource = datasource;
        }

        private void btnShowNewProgram_Click(object sender, EventArgs e)
        {
             PrepareList(menuNewProgram.Checked, menuExistingProgram.Checked, menuConflictProgram.Checked);
        }

        private void btnShowExistingPrograms_Click(object sender, EventArgs e)
        {
            PrepareList(menuNewProgram.Checked, menuExistingProgram.Checked, menuConflictProgram.Checked);
        }

        private void btnShowConflictPrograms_Click(object sender, EventArgs e)
        {
            PrepareList(menuNewProgram.Checked, menuExistingProgram.Checked, menuConflictProgram.Checked);
        }

        private void dgvProgramList_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = true;
        }

        private void dgvProgramList_SelectionChanged(object sender, EventArgs e)
        {
            
        }

        private void dgvProgramList_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            
        }

        

        private void dgvProgramList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            
        }

        private void btnSaveProgram_Click(object sender, EventArgs e)
        {
            _program=programEditor1.SaveProgram();
            //BLLFactory.ProgramBLL.Refresh();
            //dgvProgramList.Refresh();
            LoadProgramList();
            SearchProgramDisplayer();
            //dgvProgramList.DataSource = PrepareList(btnShowNewProgram.Checked, btnShowExistingPrograms.Checked, btnShowConflictPrograms.Checked);
            dgvProgramList.Rows[_selectedindex].Selected = true;
            dgvProgramList.FirstDisplayedScrollingRowIndex = _firstrowindex;
        }


        private void splitContainer2_Panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void cbExistingItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            Program p=BLLFactory.ProgramBLL.Get((Guid)cbExistingItems.SelectedValue);
            if (p != null)
            {
                lblDescription.Text = p.Description;
                lblName.Text = p.Name;
                //lblType.Text = p.Subcategory.Parent.Name + "-" + p.Subcategory.Name;
            }
        }

        private void txtTag_TextChanged(object sender, EventArgs e)
        {

        }

        

        private void dgvProgramList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //MessageBox.Show(e.RowIndex.ToString());
            _selectedindex = e.RowIndex;
            _firstrowindex = dgvProgramList.FirstDisplayedScrollingRowIndex;
            Guid currentId = (Guid)dgvProgramList.Rows[e.RowIndex].Cells["Id"].Value;
            _program = BLLFactory.ProgramBLL.Get(currentId);
            if (_program == null)
            {
                splitContainer2.Panel1Collapsed = false;
                _savemode = SaveMode.New;
                _program = _list.Single(p => p.Id == currentId);
                cbExistingItems.DisplayMember = "Name";
                cbExistingItems.ValueMember = "Id";
                cbExistingItems.DataSource = BLLFactory.ProgramBLL.GetProgramsContain(_program.Name);
            }
            else
            {
                splitContainer2.Panel1Collapsed = true;
                _savemode = SaveMode.Update;
            }
            //BindProgram(_program);
            programEditor1.SetProgram(_program, _savemode);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (_program != null && cbExistingItems.SelectedItem != null)
            {
                TPAProgram._ExistingPrograms.Add(cbExistingItems.SelectedItem as Program);
                TPAProgram._ConflictPrograms.Remove(_program);
                _program = cbExistingItems.SelectedItem as Program;
                //BindProgram(_program);
                _savemode = SaveMode.Update;
                LoadProgramList();
            }
        }

        private void btnAddCondition_Click(object sender, EventArgs e)
        {
            frmProgramSearchCondition frmSearch = new frmProgramSearchCondition();
            frmSearch.BoundProgramList = _programdisplaylist.AsQueryable();
            frmSearch.ShowDialog(this);
            if (frmSearch.NewFilter != null)
                _filterlist.Add(frmSearch.NewFilter);
            BindFilter();
            frmSearch.Dispose();
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            if (lstFilters.SelectedIndex != -1)
            {
                _filterlist.RemoveAt(lstFilters.SelectedIndex);
                lstFilters.Items.RemoveAt(lstFilters.SelectedIndex);
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            SearchProgramDisplayer();            
        }

        void SearchProgramDisplayer()
        {
            Expression<Func<ProgramDisplayer, bool>> predicate = PredicateBuilder.True<ProgramDisplayer>();
            foreach (Filter f in _filterlist)
            {
                if (f.Connector == FilterConnectorType.AND)
                    predicate = predicate.And<ProgramDisplayer>(LambdaExpressionHelper.ExpressionBuilder(f));
                else
                    predicate = predicate.Or<ProgramDisplayer>(LambdaExpressionHelper.ExpressionBuilder(f));
            }
            dgvProgramList.DataSource = _programdisplaylist.AsQueryable().Where(predicate).ToList();
        }

        private void splitContainer3_Panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void btnShowSearchPanel_Click(object sender, EventArgs e)
        {
            splitContainer3.Panel1Collapsed = !btnShowSearchPanel.Checked;
        }

        private void splitContainer3_Resize(object sender, EventArgs e)
        {
            if (!splitContainer3.Panel1Collapsed)
                splitContainer3.SplitterDistance = 150;
        }





    }

    public enum SaveMode
    {
        New, Update
    }

    public class ListItem
    {
        public string Text { get; set; }
        public string Value { get; set; }

        public override bool Equals(object obj)
        {
            try
            {
                return ((ListItem)obj).Value == this.Value;
            }
            catch
            {
                return false;
            }
            //return base.Equals(obj);
        }

        public override string ToString()
        {
            return Value;
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
    }

    


}
